//
//  LRComposeTextView.swift
//  WeiboX
//
//  Created by admin on 10/12/2016.
//  Copyright © 2016 iOS_Objective-C. All rights reserved.
//

import UIKit

class LRComposeTextView: UITextView {
	
	private lazy var placeHolderLabel: UILabel = {
		let label = UILabel()
		label.text = "placeHolder"
		
		label.textColor = .lightGray
		label.numberOfLines = 0
		label.font = .systemFont(ofSize: 12)
		label.sizeToFit()
		return label
	}()
	
	var placeHolder: String? {
		didSet {
			placeHolderLabel.text = placeHolder
		}
	}
	
	override var font: UIFont? {
		didSet {
			if font != nil {
				placeHolderLabel.font = font!
			}
		}
	}
	
	override init(frame: CGRect, textContainer: NSTextContainer?) {
		super.init(frame: frame, textContainer: textContainer)
		
		setupUI()
	}
	
	required init?(coder aDecoder: NSCoder) {
		fatalError("init(coder:) has not been implemented")
	}
	
	private func setupUI() {
		// 监听文字改变的通知
		NotificationCenter.default.addObserver(self, selector: #selector(textViewDidChanged), name: NSNotification.Name.UITextViewTextDidChange, object: nil)
		
		addSubview(placeHolderLabel)
		
		placeHolderLabel.translatesAutoresizingMaskIntoConstraints = false
		
		addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 5))
		addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 8))
		addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .width, relatedBy: .equal, toItem: self, attribute: .width, multiplier: 1, constant: -10))
	}
	
	@objc private func textViewDidChanged() {
		placeHolderLabel.isHidden = hasText
	}
	
	deinit {
		NotificationCenter.default.removeObserver(self)
	}
}
